﻿@Cofe ?= {}

$ = jQuery
Entry = Cofe.Entry
EntryItemList = Cofe.EntryItemList
EntryItem = Cofe.EntryItem
EntryList = Cofe.EntryList
EntryTreeItem = Cofe.EntryTreeItem
Link = Cofe.Link
utils = Cofe.utils



class EntryTreeView extends Spine.Controller    
  childItemTemplate : $.templates("#treeItemTemplate")
  childHeaderTemplate : $.templates("#treeHeaderTemplate") 
  treeItemStates : [ "collapsed", "expanding", "expanded" ] #Jquery Icon dictionary - http://www.petefreitag.com/cheatsheets/jqueryui-icons/
  rootEntryItems : []
  bountyPath : undefined
  #bountyPath : "{cofe}/dir2/dir2a"
  selectedItem : undefined

  elements : 
    ".subEntries:first" : "uiRootEntryList"

  entryItemConstructor : (entry) =>
    #console.log "entryItemConstructor" + entry.path
    return new EntryTreeItem({
        treeView : @
        entry : entry
        el : $("<li>")
        #childTemplate : @childTemplate
    })


  constructEntryItemList : (el) ->
    entryItemList = new EntryItemList({ 
      waypoint : false, 
      select : 'one', 
      entryFilter : (entry) -> entry.isContainer(),
      entryItemConstructor : @entryItemConstructor
    })

    if el isnt undefined then entryItemList.el = el
    return entryItemList

  addRootEntry : (entry) =>
    entryTreeItem = @entryItemConstructor(entry)
    @rootEntryItems.push(entryTreeItem)
    @render()    

  render : () =>    
    @remove()
    #console.log @rootEntryItems
    for root in @rootEntryItems
      #console.log root.render()
      @uiRootEntryList.append(root.render())
      #root.expand()

  remove : () =>
    @uiRootEntryList.empty()

  collectBounty : (entryTreeItem) ->
    @bountyPath = undefined
    @selected(entryTreeItem)

  # Called by EntryTreeItem's EntryItemList.fetchFailed event.
  error : (sender, errorStr, url) =>
    @trigger("error", sender, errorStr, url)

  select : (bountyPath) ->
    #console.log "select "+  bountyPath
    @bountyPath = bountyPath
    for root in @rootEntryItems
      root.checkBounty()

  selected : (entryTreeItem) =>
    @selectedItem?.selected = false
    @selectedItem?.refresh(false)

    @selectedItem = entryTreeItem
    @selectedItem?.selected = true
    @selectedItem?.refresh(false)
    @selectedItem?.expand()
    
    @trigger("selectionChanged", @, entryTreeItem.entry)

Cofe.EntryTreeView = EntryTreeView